package com.example.service.impl;

import com.example.mapper.EmployeeMapper;
import com.example.mapper.UserMapper;
import com.example.model.Employee;
import com.example.model.EmployeeStatus;
import com.example.model.User;
import com.example.model.UserStatus;
import com.example.model.dlo.RegisterRequest;
import com.example.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@RequiredArgsConstructor
@Service
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;
    private final EmployeeMapper employeeMapper;
    @Override
    public User authenticate(String username, String password) {
        User user=userMapper.selectUserByUsernameAndPassword(username,password);
        if(user!=null){
            return user;
        }
        else{
            return null;
        }
    }

    @Override
    public boolean register(RegisterRequest registerRequest) {
        if (userMapper.selectUserByUsernameAndPassword(registerRequest.getUsername(),registerRequest.getPassword())!=null){
            return false;
        }
        Employee employee=new Employee();
        User  user=new User();
        employee.setId(employeeMapper.countEmployees()+1);
        employee.setName(registerRequest.getEmployeeName());
        employee.setGender(registerRequest.getGender());
        employee.setBirthDate(registerRequest.getBirthDate());
        employee.setEmail(registerRequest.getEmail());
        employee.setPhone(registerRequest.getPhone());
        employee.setAddress(registerRequest.getAddress());
        employee.setHireDate(registerRequest.getHireDate());
        employee.setDepartmentId(4);
        employee.setStatus(EmployeeStatus.valueOf("在职"));
        employee.setCreateTime(LocalDateTime.now());     // 👈 添加
        employee.setUpdateTime(LocalDateTime.now());
        user.setId(userMapper.countUsers()+1);
        user.setUsername(registerRequest.getUsername());
        user.setPassword(registerRequest.getPassword());
        user.setEmployeeId(employee.getId());
        user.setRoleId(3);
        user.setStatus(UserStatus.valueOf("启用"));
        user.setEmail(registerRequest.getEmail());
        user.setCreateTime(java.time.LocalDateTime.now());
        user.setUpdateTime(java.time.LocalDateTime.now());
        employeeMapper.insertEmployee(employee);
        userMapper.insertUser(user);
        return true;
    }

    @Override
    public void UpdateUser(User user) {
        userMapper.updateById(user);
    }

    @Override
    public void updatePassword(int id, String newPassword) {
        userMapper.updatePasswordById(id,newPassword);
    }
}
